import { Controller, Get, Post, Body, Param } from '@nestjs/common';
import errors from './errors';
import { getConfig, getDatabaseConfigPath, loadDatabaseConfig } from './config';
import { Database } from './database';
import * as fs from 'fs';

@Controller()
export class AppController {
    @Get()
    getHello(): string {
        return "database-service is running";
    }

    @Get(["/alter/:file/:table", "/alter/:file", "/alter"])
    async alter(@Param() d: { table: string, file: string }) {//@routeData d: { table: string, file: string }
        if (!d.table && !d.file) {
            await AppController.alterAll();
            return { message: "success" };
        }

        if (d.file && !d.table) {
            await AppController.alterFile(d.file);
            return { message: "success" };
        }

        await AppController.alterTable(d.file, d.table);
        return { message: "success" };
    }

    static async alterAll() {
        let dbConfigPath = getDatabaseConfigPath();
        let files = fs.readdirSync(dbConfigPath);
        files = files.filter(f => f.endsWith(".yaml")).map(f => f.replace(".yaml", ""));
        // files.forEach(async file => {
        //     await this.alterFile(file);
        // })
        await Promise.all(files.map(async file => this.alterFile(file)));
    }

    static async alterFile(file: string) {
        let dbConfig = loadDatabaseConfig(file);
        for (let table in dbConfig.tables) {
            await this.alterTable(file, table);
        }
    }

    static async alterTable(file: string, table: string) {
        table = table.toLowerCase();
        let config = getConfig();
        let dbConfig = loadDatabaseConfig(file);
        let database = new Database(config.conns[dbConfig.conn]);
        let tables = await database.getTableNames();
        let columnsConfig = dbConfig.tables[table];
        if (!columnsConfig)
            throw errors.tableConfigNotFound(table, file);

        if (!tables.includes(table)) {
            await database.createTable(table, columnsConfig);
        }
        else {
            await database.alterTable(table, columnsConfig);
        }
    }
}


